package com.inspectortime.webapp.inspector;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.inspectortime.domain.InspectorCompany;
import com.inspectortime.repository.Repository;
import com.inspectortime.webapp.payment.AuthorizeNetPaymentRequestHelper;
import com.inspectortime.webapp.payment.PaymentUtils;
import com.mkode.util.java.lang.ClassUtils;

public class PaymentGatewayValidator implements Validator {

	private Repository repository;

	public void setRepository(Repository repository) {
		this.repository = repository;
	}

	public boolean supports(Class clazz) {
		return ClassUtils.isInstanceOf(clazz, InspectorCompany.class);
	}

	public void validate(Object target, Errors errors) {
		InspectorCompany company = (InspectorCompany) target;
		if (StringUtils.isBlank(company.getSimLoginId())) {
			errors.reject("inspector.company.missing.login.id",
					"Login ID is required.");
		} else if (company.getSimLoginId().length() < 4) {
			errors.reject("inspector.company.invalid.login.id",
					"Login ID is too short.");
		}

		if (StringUtils.isBlank(company.getSimTransactionKey())) {
			errors.reject("inspector.company.missing.transaction.key",
					"Transaction Key is required.");
		} else if (company.getSimTransactionKey().length() != 16) {
			errors.reject("inspector.company.invalid.transaction.key.length",
					"Transaction Key should be 16 characters.");
		}

		// No point in continuing if errors above
		if (errors.getErrorCount() > 0) {
			return;
		}
		AuthorizeNetPaymentRequestHelper paymentRequest = new AuthorizeNetPaymentRequestHelper(company
				.getSimLoginId(), company.getSimTransactionKey());
		String[] invoiceUniqueFields = PaymentUtils.generateInvoiceNumber();
		int timestamp = Integer.parseInt(invoiceUniqueFields[0]);
		int sequenceNumber = Integer.parseInt(invoiceUniqueFields[1]);
		String invoiceNumber = invoiceUniqueFields[2];
		paymentRequest.setTimestamp(timestamp);
		paymentRequest.setSequenceNumber(sequenceNumber);
		paymentRequest.setInvoiceNumber(invoiceNumber);
		
		if (!paymentRequest.execute()) {
			errors
					.reject(
							"inspector.company.invalid.transaction",
							"Invalid loginID or transaction key.");
			errors
			.reject(
					"inspector.company.invalid.transaction.log",
					paymentRequest.getExecutionLog());
		}

	}

}
